package com.augurit.common.sysmeta.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;

import com.augurit.common.base.extmodel.base.BaseTreeNode;
import com.augurit.common.base.extmodel.inner.ExtMetaColumnNode;
import com.augurit.common.base.extmodel.inner.ExtMetaOwnerNode;
import com.augurit.common.base.extmodel.inner.ExtMetaTableNode;
import com.augurit.common.dao.SysMetaTableDao;
import com.augurit.common.entity.SysMetaTable;
import com.augurit.common.sysmeta.convert.SysMetaColumnConvertor;
import com.augurit.common.sysmeta.convert.SysMetaTableConvertor;
import com.augurit.common.sysmeta.service.ISysMetaColumnService;
import com.augurit.common.sysmeta.service.ISysMetaTableService;
import com.augurit.common.sysmeta.web.form.SysMetaColumnForm;
import com.augurit.common.sysmeta.web.form.SysMetaTableForm;
import com.augurit.common.util.HqlUtils;
import com.augurit.common.util.PageUtils;

import com.augurit.wf.bi.service.IWfViewConfigService;

/**
 * 表结构元数据定义实现类
 */
@Service
@Transactional
public class SysMetaTableServiceImpl implements ISysMetaTableService{

	@Autowired
	private SysMetaTableDao sysMetaTableDao;
	
	@Autowired
	private ISysMetaColumnService sysMetaColumnService;

	
	public void delete(Long... ids) {
		if(ids != null ){
			for(Long id:ids)
				deleteCasecade(id);
		}
	}

	public SysMetaTableForm get(Long id) {
		return sysMetaTableDao.getForm(id);
	}

	public void save(SysMetaTableForm... forms) {
		if(forms != null){
			for(SysMetaTableForm form:forms){
				sysMetaTableDao.save(form);
			}
		}
	}
	
	
	/**
	 * 异步获取整个树信息
	 * @param id 
	 * @return
	 */
	public List<? extends BaseTreeNode> viewTree(String id){
		List<? extends BaseTreeNode> result = null;
		if(id != null){
			result = new ArrayList<BaseTreeNode>();
			
			//获取表节点
			if(id.equals("-1"))
				result= this.getAllOwner();
			
			//根据用户获取表
			else if(id.indexOf("owner")>=0)
				result = this.getTablesByOwner(id.split("_")[1]);
			//根据tableId获取字段节点
			else if(id.indexOf("table")>=0){
				id  = id.split("_")[1];
				result = this.getColumnsByTableId(Long.parseLong(id));
			}
		}
		 return result;
	}
	
	
	/**
	 * 给SysMetaTableForm对象加载关联的SysMetaColumnForm列表
	 * @param form
	 */
	public void loadColumnsForTable(SysMetaTableForm form){
		if(form != null){
			List<SysMetaColumnForm> columns =  sysMetaColumnService.getColumnsByTableId(form.getId());
			if(columns != null && columns.size()>0)
				form.setColumns(columns);
		}
	}
	
	/**
	 * 给列表的每个SysMetaTableForm对象加载关联的SysMetaColumnForm列表
	 * @param forms
	 */
	public void loadColumnForTableList(List<SysMetaTableForm> forms){
		if(forms != null && forms.size()>0){
			for(SysMetaTableForm form :forms)
				loadColumnsForTable(form);
		}
	}
	
	/**
	 * 关联删除,删除SysMetaTableForm以及它所关联的SysMetaColumnForm列表
	 * @param id
	 */
	public void deleteCasecade(Long id){
		if(id != null){
			List<SysMetaColumnForm> columns =  sysMetaColumnService.getColumnsByTableId(id);
			
			//删除关联
			List<Long> columnIds = SysMetaColumnConvertor.convertFormsToIds(columns);
			if(columnIds != null && columnIds.size()>0){
				Long []ids = columnIds.toArray(new Long[columnIds.size()]);
				sysMetaColumnService.delete(ids);
			}
			
			//删除本身
			this.sysMetaTableDao.delete(id);
		}
	}
	
	/**
	 * 获取所有的SysMetaTableForm列表
	 * @return
	 *//*
	public List<SysMetaTableForm> getAll(){
		List<SysMetaTableForm> forms = null;
		List<SysMetaTable> entities = this.sysMetaTableDao.getAll();
		if(entities != null && entities.size()>0)
			forms = SysMetaTableConvertor.convertEntityListToFormList(entities);
		return forms;
	}*/
	
	public Page<SysMetaTableForm> search(SysMetaTableForm form,Page<SysMetaTableForm> page,StringBuffer sb){
		if(form != null && page != null && sb != null){
			// 建立分页对象
			Page<SysMetaTable> pg = PageUtils.newPageInstance(page);
			
			// 查询条件
			if(form.getTableName() != null && form.getTableName().trim().length()>0)
				sb.append(" and ps.tableName like '%" + form.getTableName().trim() + "%'");
			
			if(form.getTableChineseComments() != null && form.getTableChineseComments().trim().length()>0)
				sb.append(" and ps.tableChineseComments like '%" +form.getTableChineseComments().trim() + "%'");
			
			if(form.getOwner() != null && form.getOwner().trim().length()>0)
				sb.append(" and ps.owner like '%" + form.getOwner().trim() +"%'");
			
			sb.append(HqlUtils.buildOrderBy(pg, "ps"));
			
			String hql = sb.toString();
			
			//查询结果
			pg = this.sysMetaTableDao.findPage(pg,hql);
			List<SysMetaTableForm> forms = SysMetaTableConvertor.convertEntityListToFormList(pg.getResult());
			PageUtils.copy(pg, forms, page);
		}
		return page;
	}
	
	/**
	 * 条件查询方法
	 * @param form
	 * @return
	 */
	public Page<SysMetaTableForm> search(SysMetaTableForm form,Page<SysMetaTableForm> page){
		if(form != null && page != null){
			StringBuffer sb =  new StringBuffer("from SysMetaTable ps where 1=1");
			return search(form,page,sb);
		}
		return page;
	}
	
	/**
	 * 条件查询方法,并过滤掉指定实体名的表
	 * @param form
	 * @return
	 */
	public Page<SysMetaTableForm> search(SysMetaTableForm form,Page<SysMetaTableForm> page,String busEntityName){
		if(form != null && page != null && busEntityName != null && busEntityName.trim().length()>0){
			StringBuffer sb =  new StringBuffer("from SysMetaTable ps where ps.entityName <>'" + busEntityName+"'");
			return search(form,page,sb);
		}
		return page;
	}
	/**
	 * 根据tableId获取字段列表,并转化为树节点
	 * @param tableId
	 * @return
	 */
	private List<ExtMetaColumnNode> getColumnsByTableId(Long tableId){
		List<ExtMetaColumnNode>  list = null;
		if(tableId != null){
			List<SysMetaColumnForm> columns = sysMetaColumnService.getColumnsByTableId(tableId);
			if(columns != null && columns.size()>0)
				list = SysMetaColumnConvertor.convertToExtNodeList(columns);
		}
		return list;
	}
	
	/**
	 * 获取树的根节点下的所有表节点
	 * @return
	 *//*
	private List<ExtMetaTableNode> getTablesByRootNode(){
		List<ExtMetaTableNode> result = null;
		List<SysMetaTableForm> tableList = this.getAll();
		if(tableList != null && tableList.size()>0){
			result = SysMetaTableConvertor.convertToExtNodeList(tableList);
		 }
		return result;
	}*/
	
	/**
	 * 获取所有的元数据树用户Ext节点
	 * @return
	 */
	public List<ExtMetaOwnerNode> getAllOwner(){
		List<String> list = this.sysMetaTableDao.getAllOwner();
		if(list != null){
			List<ExtMetaOwnerNode> nodes = SysMetaTableConvertor.convertToExtOwnerNodeList(list);
			return nodes;
		}
		return null;
	}
	
	/**
	 * 根据用户获取表
	 * @param owner
	 * @return
	 */
	public List<ExtMetaTableNode> getTablesByOwner(String owner){
		List<ExtMetaTableNode> nodes = null;
		if(owner != null){
			List<SysMetaTableForm> forms = this.sysMetaTableDao.getTablesByOwner(owner);
			if(forms != null)
				nodes = SysMetaTableConvertor.convertToExtNodeList(forms);
		}
		return nodes;
	}
	
	/**
	 * 根据用户获取表结构定义form对象列表
	 * @param owner
	 * @return
	 */
	public List<SysMetaTableForm> getAllMetaTables(){
		List<SysMetaTable> entities = sysMetaTableDao.getAll();
		return SysMetaTableConvertor.convertEntityListToFormList(entities);
	}
	
	/**
	 * 根据实体名数组获取Id数组
	 */
	public Long[] getTableIdsByEntityNames(String entityNames[]){
		return sysMetaTableDao.getTableIdsByEntityNames(entityNames);
	}
	
	public List<SysMetaTableForm> getTableByTableNames(String tableNames[]){
		
		if(tableNames != null && tableNames.length>0){
			StringBuilder sb = new StringBuilder("from SysMetaTable ps where 1=2 or ");
			sb.append(HqlUtils.buildOrCondition("ps", "tableName", tableNames));
			List<SysMetaTable> list = sysMetaTableDao.find(sb.toString());
			
			return SysMetaTableConvertor.convertEntityListToFormList(list);
		}
		return null;
	}
	
	public List<SysMetaTableForm> getTableByEntityNames(String entityNames[]){
		
		if(entityNames != null && entityNames.length>0){
			StringBuilder sb = new StringBuilder("from SysMetaTable ps where 1=2 or ");
			sb.append(HqlUtils.buildOrCondition("ps", "entityName", entityNames));
			List<SysMetaTable> list = sysMetaTableDao.find(sb.toString());
			
			return SysMetaTableConvertor.convertEntityListToFormList(list);
		}
		return null;
	}
	
	public List<SysMetaTableForm> getOtherTables(SysMetaTableForm form, String entityName){
		
		if(entityName != null && entityName.trim().length() > 0){
			
			StringBuilder hql = new StringBuilder("from SysMetaTable ps where ps.entityName <> ?");
			
			List<Object> values = new ArrayList<Object>();
			values.add(entityName);
			if(form.getEntityName() != null && form.getEntityName().trim().length() > 0){
				hql.append(" and ps.entityName like ?");
				values.add("%" + form.getEntityName() + "%");
			}
			if(form.getTableChineseComments() != null && form.getTableChineseComments().trim().length() > 0){
				hql.append(" and ps.tableChineseComments like ?");
				values.add("%" + form.getEntityName() + "%");
			}
			
			List<SysMetaTable> entities = sysMetaTableDao.find(hql.toString(), values);
			
			List<SysMetaTableForm> result =  SysMetaTableConvertor.convertEntityListToFormList(entities);
			
			return result;
		}
		return null;
		
	}
}
